<?php
class ModelRequest extends BaseModel{
	var $requester = null;
	var $nickName = null;
	var $code = null;
	var $rid = null;
	var $time = null;

	function __construct(){
		parent::__construct();
		$this->time = date("Y-m-d H:i:s");
	}

	public static function generateByNick($requester,$nickname){
		$request = new ModelRequest();
		$request -> requester = $requester;
		$request->nickName = $nickname;
		
		$code = randomDigital(6);
// 		$code = '581741';
		while (self::isVerifyCodeExist($code)){
			log_i("Verify code $code is found in database, and then re-generate it.");
			$code = randomDigital(6);
		}
		$request->code = $code;

		$request->buildRequest();
		return $request;
	}
	
	public static function findRequestByVerifyCode($code){
		if(!self::isVerifyCodeExist($code)){
			return null;
		}
		
		
		$sql = "select rid,reqs,nick,time from ps_request where code = '$code' limit 1;";
		$db = MyDB::getInstance();
		$result = $db->queryOneRow($sql);
// 		var_dump($result);
		
		$request = new ModelRequest();
		$request->rid = $result['rid'];
		$request->requester = $result['reqs'];
		$request->nickName = $result['nick'];
		$request->time = $result['time'];
		$request->code = $code;
// 		var_dump($request);
		return $request;
	}
	
	public static function deleteAllRequestWithUUID($uuid){
		$db = MyDB::getInstance();
		$sql = "DELETE FROM ps_request WHERE reqs = '$uuid'";
		$db->exec($sql);
	}

	private function buildRequest(){
		$db = parent::getMyDB();
		$sql = "INSERT INTO ps_request (reqs,nick,code,time) VALUES('$this->requester','$this->nickName','$this->code','$this->time')";
		$id = $db->insertOneRecord($sql);
		$this->rid = $id;

	}
	
	private static function isVerifyCodeExist($code){
		$db = MyDB::getInstance();
		$sql = "SELECT count(*) FROM ps_request WHERE code = '$code'";
		$ret=$db->queryOneValue($sql);
		return $ret==false?false:true;
		
	}


	public static function createTable(){
		$db = MyDB::getInstance();
		$sql_create = 'CREATE TABLE IF NOT EXISTS `ps_request` (
		`rid` int(8) NOT NULL AUTO_INCREMENT,
		`reqs` char(255) NOT NULL,
		`nick` varchar(8) NOT NULL,
		`code` char(6) NOT NULL,
		`time` datetime NOT NULL,
		PRIMARY KEY (`rid`),
		FOREIGN KEY (`reqs`) REFERENCES `ps_user` (`uuid`) ON UPDATE NO ACTION
		) ENGINE=InnoDB DEFAULT CHARSET=latin1';
		$db->exec($sql_create);
	}

	public static  function dropTable(){
		parent::dropTableByName('ps_request');
	}

}